//
//  OAuthViewController.swift
//  Webo10
//
//  Created by ChengXiwu on 2017/7/29.
//  Copyright © 2017年 ChengXiwu. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {
    
    private lazy var webView = UIWebView()
    
    // MARK: - 监听方法
    @objc fileprivate func close(){
        dismiss(animated: true, completion: nil)
    }
    
    // 自动填充用户名和密码
    @objc private func autoFill(){
        
        let js = "document.getElementById('userId').value = 'talens2004@sina.com';" + "document.getElementById('passwd').value = 'Talens2004@sina';"
        webView.stringByEvaluatingJavaScript(from: js)
    }
    
    // MARK: - 设置界面
    override func loadView() {
        view = webView
        // 设置背景颜色,重要,否则可能引起卡顿
        view.backgroundColor = UIColor.red
        
        // 设置代理
        webView.delegate = self
        
        // 设置导航栏
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(close))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .plain, target: self, action: #selector(autoFill))

    }

    // MARK: - 生命周期方法
    override func viewDidLoad() {
        super.viewDidLoad()
        // 加载授权页面
        webView.loadRequest(URLRequest(url: OAuthTools.oauth.oauthUrl))
    }
    
    deinit {
        // 销毁进度条
        SVProgressHUD.dismiss()
    }
    
}

extension OAuthViewController: UIWebViewDelegate{
    
    // 在代理方法中返回true正常执行,返回false则拦阻
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        // 判断访问的主机是否www.baidu.com
        guard let url = request.url, url.host == "www.baidu.com" else {
            return true
        }
        
        // 从百度地址的url中提取'code='是否存在
        guard let query = url.query, query.hasPrefix("code=") else {
            SVProgressHUD.showInfo(withStatus: "授权被取消")
            self.close()
            
            return false
        }
        
        // 提取授权码
        let code = query.substring(from: "code=".endIndex)
        logPrint("授权码是:" + code)
        
        // 加载AccessToken
        OAuthTools.oauth.loadAccessToken(code: code) { (isSuccess, msg)->() in
            if !isSuccess {
                SVProgressHUD.showInfo(withStatus: msg)
                self.close()
                return
            }
            logPrint("验证成功,进入欢迎界面")
            // 销毁当前控制器,dismiss不会立即将控制器销毁
            self.dismiss(animated: false) {
                // 发送切换界面通知
                NotificationCenter.default.post(name: WBSwitchRootViewControllerNotification, object: "welcome")
            }
        }
        return false
    }
    
    
}
